<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('出资人类型')" prop="investorType">
            <el-select v-model="form.investorType" :placeholder="$t('出资人类型')" :disabled="form.id !== undefined && form.id !== '' && form.id !== null" @change="changeNameByTypeToSelect">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="form.investorType === 'fund' ? $t('基金名称') : (form.investorType === 'spv' ? $t('SPV名称') : $t('出资人名称'))" prop="investorName">
            <MainBodySelect
              v-if="form.investorType === 'fund' || form.investorType === 'spv'"
              v-model="form.investorId"
              :parameters="form.investorType"
              :disabled="form.id !== undefined && form.id !== '' && form.id !== null"
              @changeData="lpDictsSelect"
            />
            <el-autocomplete
              v-else
              v-model="form.investorName"
              :fetch-suggestions="changeNameByQuerySearch"
              :placeholder="$t('出资人名称')"
              class="fundInvestorSelect"
              :maxlength="100"
              :highlight-first-item="true"
              :disabled="form.id !== undefined && form.id !== '' && form.id !== null"
              @select="lpDictsSelect"
            >
              <template slot="append">
                <!-- <i slot="suffix" class="el-icon-edit el-input__icon" /> -->
                <template slot-scope="{ item }">
                  <div class="value">{{ item.value }}</div>
                </template>
                <el-button type="primary" icon="el-icon-edit" @click="addCustomer">{{ $t('添加客户') }}</el-button>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计认缴时间')" prop="estimatedTime">
            <DatePicker
              v-model="form.estimatedTime"
              :placeholder="$t('预计认缴时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('投资意向金额') + $t('金额单位')" prop="amountIntention">
            <Money v-model="form.amountIntention" unit="w" :placeholder="$t('投资意向金额')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('募集阶段')" prop="lpStage">
            <dictSelect
              v-model="form.lpStage"
              :clearable="true"
              dictionary="crm_lp_stage"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('最终认缴金额') + $t('金额单位')" prop="finalAmount">
            <Money v-model="form.finalAmount" unit="w" :placeholder="$t('最终认缴金额')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('最终认缴日期')" prop="finalDate">
            <DatePicker
              v-model="form.finalDate"
              :placeholder="$t('最终认缴日期')"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('银行户名')" prop="bankName">
            <el-input v-model="form.bankName" :placeholder="$t('银行户名')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('银行卡号')" prop="bankNumber">
            <el-input v-model="form.bankNumber" :placeholder="$t('银行卡号')" show-word-limit maxlength="25" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('开户行')" prop="accountBank">
            <el-input v-model="form.accountBank" :placeholder="$t('开户行')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('支行')" prop="branch">
            <el-input v-model="form.branch" :placeholder="$t('支行')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button v-hasPermi="['fund:intentionInvest:edit']" type="primary" @click="submitForm">{{ $t("保存") }}</el-button>
    </div>
    <!-- 添加或修改客户管理对话框 -->
    <el-dialog
      :title="$t('添加客户')"
      :visible.sync="formOpen"
      custom-class="dialogForm"
      width="70%"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <lpBaseForm ref="lpBaseForm" @senddata="sendData" />
    </el-dialog>
  </div>
</template>
<script>
    import { saveFundIntentionInvest, getFundIntentionInvest } from '@/api/fund/intentionInvest/fundIntentionInvest'
    import { changeNameByTypeAndName, checkInvestor } from '@/api/fund/investor/fundInvestor'
    import lpBaseForm from '@/views/fund/lpBase/lpBaseForm.vue'
    import MainBodySelect from '@/components/MainBodySelect'
    import { saveLpBase } from '@/api/fund/lpBase/lpBase'
    export default {
        components: {
          MainBodySelect,
          lpBaseForm
        },
        data() {
            /* const checkLpNameValidator = (rule, value, callback) => {
              console.log(rule, value, callback)
              checkLpName(this.$route.query.id, this.form.investorId).then(response => {
                if (response.data > 0 && !this.form.id) {
                  callback(new Error(this.$t('出资人已存在,不能重复添加!')))
                } else {
                  callback()
                }
              })
            }*/
            return {
                // 表单参数
                form: {},
                formOpen: false,
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {
                  investorType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  investorName: [{ required: true, validator: this.checkLpNameValidator,	trigger: 'change' }]
                  // amountIntention: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // lpOptions: [],
                typeOptions: [],
                whereIsCheckInvestor: false,
                investOptionList: []
            }
        },
        created() {
          // 类型字典2
          this.getDicts('lp_type_intended').then(response => {
            response.data.forEach(item => {
              this.typeOptions.push(item)
            })
          })
        },
      mounted() {
        // this.investOptionList = this.loadInvestAll()
      },
      methods: {
            // 初始化数据
            init(data) {
                if (data != null && data.id !== undefined) {
                    getFundIntentionInvest(data.id).then(response => {
                      // 加载名称
                      this.changeNameByTypeToSelect()
                      this.form = response.data
                    })
                } else {
                    this.reset()
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                fundId: this.$route.query.id,
                investorId: undefined,
                investorName: undefined,
                investorType: undefined,
                estimatedTime: undefined,
                lpStage: '1',
                amountIntention: undefined,
                finalAmount: undefined,
                finalDate: undefined,
                bankName: undefined,
                bankNumber: undefined,
                accountBank: undefined,
                branch: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm(that) {
              try {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
              } catch (e) {
                console.log(e)
                // 关闭form页面遮罩层
                that.loading = false
                // 关闭form页面
                that.$parent.$parent.formOpen = false
                // 刷新list页面
                that.$parent.$parent.getList()
              }
            },
            // 接受子页面传递值
            getList() {
              this.loading = false
            },
            /** 提交按钮 */
            submitForm: function() {
              this.$refs['form'].validate(valid => {
                if (valid) {
                  var that = this
                  that.loading = true
                  if (this.whereIsCheckInvestor) {
                    // 询问是否完善出资人信息
                    that.$confirm(that.$t('是否完善出资人信息?'), that.$t('提示'), {
                      confirmButtonText: that.$t('完善'),
                      cancelButtonText: that.$t('跳过'),
                      type: 'warning'
                    })
                      .then(function() {
                        // 完善
                        that.formOpen = true
                        that.$nextTick(() => {
                          that.$refs.lpBaseForm.init(null)
                          // 全称
                          that.$refs.lpBaseForm.form.name = that.form.investorName
                          // 简称
                          that.$refs.lpBaseForm.form.shortName = that.form.investorName
                          // 关注等级
                          that.$refs.lpBaseForm.form.followLevel = 'ybgz'
                          // 业务经理
                          that.$refs.lpBaseForm.form.manager = [that.$store.state.user.userId]
                          // 客户类型
                          that.$refs.lpBaseForm.form.type = that.form.investorType
                        })
                      })
                      .catch(function() {
                        that.loading = true
                        const data = {
                          type: that.form.investorType,
                          name: that.form.investorName,
                          shortName: that.form.investorName,
                          followLevel: 'ybgz',
                          manager: [that.$store.state.user.userId]
                        }
                        saveLpBase(data).then(response => {
                          if (response.code === 200) {
                            that.form.investorId = response.data.id
                            that.saveSubmitForm(that)
                          } else {
                            that.msgError(that.$t('发生异常!'))
                            that.loading = false
                          }
                        })
                      })
                  } else {
                    this.saveSubmitForm(that)
                  }
                } else {
                  this.locationError(document)
                }
              })
            },
            /** 提交按钮 */
            saveSubmitForm: function(that) {
              this.loading = true
              saveFundIntentionInvest(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(this.$t('保存成功'))
                  this.closeForm(that)
                } else {
                  this.msgError(response.msg)
                }
                this.loading = false
              })
            },
            // 添加新到的客户
            addCustomer() {
              this.formOpen = true
              this.title = this.$t('添加客户管理')
              this.$nextTick(() => {
                this.$refs.lpBaseForm.init(null)
              })
            },
            sendData: function(data) {
              this.form.investorName = data.name
              this.form.investorType = data.type
              this.form.investorId = data.id
            },
            // 根据类型 改变名称下拉
            changeNameByQuerySearch(queryString, cb) {
              // queryString = this.form.investorType
              console.log(queryString)
              const investOptionList = this.loadInvestAll(this.form.investorType, queryString)
              // const results = queryString ? investOptionList.filter(this.createFilter(queryString)) : investOptionList
              // 调用 callback 返回建议列表的数据
              cb(investOptionList)
            },
            createFilter(queryString) {
              return (restaurant) => {
                return (restaurant.value.toLowerCase().includes(queryString.toLowerCase()))
              }
            },
            loadInvestAll(type, name) {
              var temp = []
              changeNameByTypeAndName(type, name).then(response => {
                if (response.data !== null) {
                  response.data.forEach(item => {
                    temp.push({ 'id': item.id, 'value': item.name })
                  })
                }
              })
              return temp
            },
            lpDictsSelect(item) {
              console.log(item)
              if (item.svalue) {
                this.form.investorId = item.svalue
                this.form.investorName = item.name
              } else {
                this.form.investorId = item.id
                this.form.investorName = item.value
              }
            },
            // 根据类型 改变名称下拉
            changeNameByTypeToSelect: function() {
              this.form.investorId = undefined
              this.form.investorName = undefined
            },
            // 校验出资人是否存在
            async checkLpNameValidator(rule, value, callback) {
              if (this.form.investorType === 'GR' || this.form.investorType === 'JG') {
                var that = this
                that.whereIsCheckInvestor = false
                if (that.form.investorName === undefined || that.form.investorName === '') {
                  return callback(new Error(that.$t('必填信息')))
                }
                if (that.form.id === undefined || that.form.id === null || that.form.id === '') {
                  var checkRes = await checkInvestor(that.form.investorType, that.form.investorName)
                  if (checkRes.data.length < 1 && (that.form.investorType === 'JG' || that.form.investorType === 'GR')) {
                    that.whereIsCheckInvestor = true
                    console.log('当前出资人不存在, 为手动输入.' + that.form.investorType)
                  } else {
                    this.form.investorId = checkRes.data[0].id
                    console.log(this.form.investorId)
                  }
                  return callback()
                } else {
                  return callback()
                }
              } else {
                return callback()
              }
            }
        }
    }
</script>
